package cn.tedu.yl.base.response;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.UUID;

@Service
public class TokenService {
//    String uuid = UUID.randomUUID().toString();
    private String secretKey = "joe666"; // 应该是一个复杂的密钥
    private long tokenExpirationAfterSeconds = 18000; // Token有效时长，例如3小时

    public String createToken(String username) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 添加构建Token所需的参数
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(new Date(nowMillis + tokenExpirationAfterSeconds * 1000)) // 设置过期时间
                .signWith(SignatureAlgorithm.HS512, secretKey) // 使用密钥和算法进行签名
                .compact();
    }

    //效验token
    public boolean checkToken(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


}
